from common.models.check_report import CheckReport
from flask import Blueprint, request, make_response, redirect
import json, requests
from application import app, db
import datetime
from common.libs.Helper import dingtalkpost, dicgetkey
from config.dingtalk_setting import column, vacationdic
from common.models.user import User
from common.models.user_change import UserChange
from common.models.user_resign import UserResign
from common.models.department import Department

from common.libs.DataHelper import getCurrentTime, getCurrentDate
from sqlalchemy import and_, or_, func
from application import db
import urllib.parse
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
from dingtalk import SecretClient, model

report_page = Blueprint("report_page", __name__)

client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式


@report_page.route('/sendreport', methods=['GET', 'POST'])
def sendreport():
    userlist = [659,661,739,805,857]
    date = getCurrentDate()
    for i in userlist:
        user = User.query.filter_by(id=i).first()
        userid = user.userid
        base_url = 'http://101.132.227.54:88/report?date=' + date
        encodeurl = urllib.parse.quote(base_url)
        dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
        normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

        msg = {
            "msgtype": "action_card",
            "action_card": {
                "title": "人力资源月报",
                "markdown": "![](http://upload.guanzhuoran.cn/report.png) \n  #### 数据统计日期：" + date,
                "btn_orientation": "1",
                "btn_json_list": [
                    {
                        "title": "查看详情",
                        "action_url": normalurl,
                    },
                ]
            }
        }
        a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userid.split())

    return json.dumps("推送成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@report_page.route('/makereport', methods=['GET', 'POST'])
def makereport():
    todaystr=request.json.get('date')
    # today = datetime.date.today()
    todaydatetime = datetime.datetime.strptime(todaystr, '%Y-%m-%d')
    today = datetime.datetime.date(todaydatetime)
    first = today.replace(day=1)
    # last_month = first - datetime.timedelta(days=1)
    etime = today - datetime.timedelta(days=1)
    stime = etime.strftime("%Y-%m") + "-01"
    # stime = last_month.strftime("%Y-%m") + "-01"

    interview = User.query.filter(User.interviewdate >= stime, User.interviewdate < etime).order_by(User.interviewdate).all()
    employ = User.query.filter(User.employdate >= stime, User.employdate < etime).order_by(User.employdate).all()
    induction = User.query.filter(User.inductiondate >= stime, User.inductiondate < etime).order_by(User.inductiondate).all()
    change = UserChange.query.filter(UserChange.changedate >= stime, UserChange.changedate < etime).order_by(UserChange.changedate).all()
    resign = UserResign.query.filter(UserResign.resigndate >= stime, UserResign.resigndate < etime).order_by(UserResign.resigndate).all()

    interviewnum = len(interview)
    employnum = len(employ)
    inductionnum = len(induction)
    changenum = len(change)
    resignnum = len(resign)
    usernum = User.query.filter(or_(User.status == 4, User.status == 1)).count()
    pusernum = User.query.filter(User.status == 4).count()

    interviewinfo = []
    for item in interview:
        temp = dict(id=item.id, department=str(item.department), name=item.name,
                    interviewdate=str(item.interviewdate)[0:10]
                    )
        interviewinfo.append(temp)

    employinfo = []
    for item in employ:
        temp = dict(id=item.id, department=str(item.department), name=item.name,
                    employdate=str(item.employdate)[0:10]
                    )
        employinfo.append(temp)

    inductioninfo = []
    for item in induction:
        temp = dict(id=item.id, department=str(item.department), name=item.name,
                    inductiondate=str(item.inductiondate)[0:10]
                    )
        inductioninfo.append(temp)

    changeinfo = []
    for item in change:
        temp = dict(id=item.userid, name=str(item.user.name), bdep=item.bdep.name, adep=item.adep.name, bpost=item.bpost,
                    apost=item.apost,
                    changedate=str(item.changedate)[0:10]
                    )
        changeinfo.append(temp)

    resigninfo = []
    for item in resign:
        temp = dict(id=item.userid, name=str(item.user.name), department=str(item.user.department),
                    resigndate=str(item.resigndate)[0:10]
                    )
        resigninfo.append(temp)

    res = {"interviewnum": interviewnum, "employnum": employnum, "inductionnum": inductionnum, "changenum": changenum,
           "resignnum": resignnum, "usernum": usernum, "pusernum": pusernum, "interviewinfo": interviewinfo,
           "changeinfo": changeinfo, "resigninfo": resigninfo,
           "employinfo": employinfo, "inductioninfo": inductioninfo}
    return json.dumps(res, ensure_ascii=False)

